from django.shortcuts import HttpResponse
from rest_framework.renderers import JSONRenderer

from base.errcode import err_number


class JSONResponse(HttpResponse):
    """
    用于返回JSON数据.
    """

    def __init__(self,code='x',data='',total=0,**kwargs):
        if not total:
            total = 0
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        try:
            if code:
                content = '{"code":' \
                          + str(code) \
                          + ',"msg":"' \
                          + err_number[str(code)] \
                          + '","data":[]}'
            else:
                content = '{"code":'\
                          +str(code)\
                          +',"msg":"'\
                          +err_number[str(code)]\
                          +'","total":'\
                          +str(total)\
                          +',"data":'\
                          +str(content,encoding="utf-8")\
                          +'}'
        except:
            content = '{"code":' \
                      + str(code) \
                      + ',"msg":"无效状态码","data":[]}'
        super(JSONResponse, self).__init__(content, **kwargs)